import { Context } from 'egg';

export default () => {
  return async (ctx: Context, next: () => Promise<any>) => {
    // 获取配置的忽略路径
    const { ignore = [] } = ctx.app.config.jwtAuth || {};
    
    // 检查当前路径是否需要跳过JWT验证
    const shouldIgnore = ignore.some((pattern: string) => {
      if (pattern.includes(':')) {
        // 处理动态路由参数
        const regex = new RegExp('^' + pattern.replace(/:[^/]+/g, '[^/]+') + '$');
        return regex.test(ctx.path);
      }
      return ctx.path === pattern;
    });

    if (shouldIgnore) {
      await next();
      return;
    }

    // 获取token
    const token = ctx.get('authorization')?.replace('Bearer ', '') || ctx.query.token;

    if (!token) {
      ctx.status = 401;
      ctx.body = {
        code: 401,
        message: '未提供认证令牌',
        data: null,
      };
      return;
    }

    try {
      // 验证token
      const decoded = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
      ctx.state.user = decoded;
      await next();
    } catch (err) {
      const errData = JSON.parse(JSON.stringify(err));
      const errName = [
        'TokenExpiredError',
        'JsonWebTokenError'
      ]
      if(errData.name && errName.includes(errData.name)) {
        ctx.body = {
          code: 401,
          message: err?.message,
          data: null,
        };
      } else {
        ctx.body = {
          code: -1,
          message: err?.message,
          data: null,
        };
      }
    }
  };
};